package com.mgface.client;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Arrays;

/**
 * @author wanyuxiang
 * @version 1.0
 * @project Java10Demo
 * @create 2018-08-08 17:56
 **/
public class Client {
	@SuppressWarnings("unchecked")
	public static <T> T get(final Class<?> serviceInterface, final InetSocketAddress addr){
		return (T)Proxy.newProxyInstance(serviceInterface.getClassLoader(),new Class[]{serviceInterface},(proxy, method, args)->{
			Socket socket = new Socket();
			socket.connect(addr);
			try(ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream())){
                System.out.println("接口名称:"+serviceInterface.getName());
				oos.writeUTF(serviceInterface.getName());
                System.out.println("方法名称:"+method.getName());
				oos.writeUTF(method.getName());
                System.out.println("方法的参数类型:"+ Arrays.asList(method.getParameterTypes()));
				oos.writeObject(method.getParameterTypes());
                System.out.println("传递的参数为:"+ Arrays.asList(args));
				oos.writeObject(args);
				return ois.readObject();
			}
		});
	}
}
